<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试题编号" prop="questionId">
        <el-input
          v-model="queryParams.questionId"
          placeholder="请输入试题编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" >
        <el-input
          v-model="queryParams.course"
          placeholder="请输入查询的课程"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题类型" >
          <el-select style="width: 200px;" v-model="queryParams.questionType" placeholder="请选择试题类型">
            <el-option
              v-for="dict in exam_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="试题难度" prop="level">
         <el-select style="width: 200px;" v-model="queryParams.level" placeholder="请选择试题难度">
            <el-option
              v-for="dict in exam_question_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="课程章节" prop="section">
        <el-input
          v-model="queryParams.section"
          placeholder="请输入课程章节"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['module:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['module:question:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试题编号" align="center" prop="questionId" />
      <el-table-column label="课程名称" align="center" prop="course" />
      <el-table-column label="试题内容" align="center">
  <template #default="scope">
    {{ scope.row.question.length > 5 ? scope.row.question.slice(0, 5) + '...' : scope.row.question }}
  </template>
</el-table-column>
      <el-table-column label="试题类型" align="center"  >
         <template #default="scope">
    {{ proxy.selectDictLabel(exam_question_type, scope.row.questionType) }}
  </template>
      </el-table-column>
      <el-table-column label="正确答案" align="center" prop="answer" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="难度等级" align="center"  >
           <template #default="scope">
    {{ proxy.selectDictLabel(exam_question_level, scope.row.level) }}
  </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['module:question:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['module:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题库管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="course">
          <el-input v-model="form.course " placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="试题内容" prop="question">
          <el-input v-model="form.question" placeholder="请输入试题内容" />
        </el-form-item>
        <el-form-item label="试题类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择试题类型">
            <el-option
              v-for="dict in exam_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="A选项" >
          <el-input v-model="form.aOption" placeholder="请输入A选项" /> 
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="B选项" >
          <el-input v-model="form.bOption" placeholder="请输入A选项" />  
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="C选项" >
          <el-input v-model="form.cOption" placeholder="请输入A选项" />   
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="D选项" >
          <el-input v-model="form.dOption" placeholder="请输入A选项" />   
        </el-form-item>
        <el-form-item label="正确答案" prop="answer">
          <template #label>
            <span>
              <el-tooltip content="输入时请需要严格按照格式！！！规范：1.输入的符号全部使用中文符号，
              2.请不要在答案中随意添加空格，3.选择题答案只填写大写T/F，选择题答案只填写大写A/B/C/D，
              填空题答案两个答案之间使用中文逗号，隔开，一个答案有多个备选项请使用中文括号（）
              （例如：答案1（备选1，备选2），答案2）"
               placement="top">
                 <el-icon><question-filled /></el-icon>
              </el-tooltip>
              答案
           </span>
          </template>
          <el-input v-model="form.answer" :placeholder="answerTips" />
        </el-form-item>
        <el-form-item label="题目解析" prop="analysis">
          <el-input v-model="form.analysis" placeholder="请输入题目解析" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="form.score" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="难度等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择试题难度等级">
            <el-option
              v-for="dict in exam_question_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程章节" prop="section">
          <el-input v-model="form.section" placeholder="请输入课程章节" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/module/question"
import { computed, onMounted } from "vue";
import { useRoute } from 'vue-router'



const { proxy } = getCurrentInstance()
const { exam_question_type, exam_question_level } = proxy.useDict('exam_question_type', 'exam_question_level')

const route = useRoute()
const questionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const selectionQuestionType=ref("")
const delIds=ref({})
//正确答案输入框提示
const answerTips = computed(() => { 
  if(form.value.questionType==1){
    return "判断题请输入大写T/F"
  }else if(form.value.questionType==2){ 
    return "选择题请输入大写A/B/C/D"
  }else if(form.value.questionType==3){ 
    return "填空题答案请使用中文字符逗号，隔开答案"
  }else{
    return ""
  }
})


// 自定义答案验证规则
const validateAnswer = (rule, value, callback) => {
  if (!value) {
    callback(new Error('正确答案不能为空'));
    return;
  }
  
  const type = form.value.questionType;
  
  // 判断题验证
  if (type == 1) {
    if (!/^[TF]$/.test(value)) {
      callback(new Error('判断题答案只能是T或F'));
    } else {
      callback();
    }
  }
  // 选择题验证
  else if (type == 2) { 
    if (!/^[A-D]$/.test(value)) {
      callback(new Error('选择题答案只能是A、B、C或D'));
    } else {
      callback();
    }
  }
  // 填空题验证
  else if (type == 3) { 
    // 检查中文逗号分隔
    if (!value.includes('，')) {
      callback(new Error('填空题答案请使用中文逗号分隔多个答案'));
      return;
    }
    
    // 检查是否有空格
    if (/\s/.test(value)) {
      callback(new Error('答案中不能包含空格'));
      return;
    }
    
    // 检查是否使用中文符号
    if (/[a-zA-Z0-9],/.test(value)) {
      callback(new Error('请使用中文逗号分隔答案'));
      return;
    }
    
    // 检查括号格式
    const brackets = value.match(/[()]/g) || [];
    if (brackets.length % 2 !== 0) {
      callback(new Error('括号必须成对出现'));
      return;
    }
    
    callback();
  }
  // 其他类型
  else {
    callback();
  }
};

const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    questionId: null,
    level: null,
    section: null,
    course: null,
    questionType: null
  },
  rules: {
    course: [
      { required: true, message: "课程名称不能为空", trigger: "change" }
    ],
    question: [
      { required: true, message: "试题内容不能为空", trigger: "blur" }
    ],
    answer: [
      { required: true, message: "正确答案不能为空", trigger: "blur" },
      { validator: validateAnswer, trigger: "blur" } // 添加自定义验证
    ],
    score: [
      { required: true, message: "分数不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "难度等级不能为空", trigger: "blur" }
    ],
    questionType: [
      { required: true, message: "试题类型不能为空", trigger: "blur" }
    ],
    course:[
      { required: true, message: "试题类型不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询题库管理列表 */
function getList() {
  loading.value = true
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    questionId: null,
    course:queryParams.value.course,
    question: null,
    answer: null,
    analysis: null,
    score: 2,
    level: '1',
    section: null,
    questionType: '1',
    aOption:null,
    bOption:null,
    cOption:null,
    dOption:null,
  }
  proxy.resetForm("questionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
    queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    questionId: null,
    level: null,
    section: null,
    questionType: null,
    course:route.params.course
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  //清空
 delIds.value={
  judgeQuestionIds:[],
  multiQuestionIds:[],
  fillQuestionIds:[],
 }
 //遍历分组
   selection.forEach(item => {
    const id = item.questionId
    const type = item.questionType

    if (type == 1) {
      delIds.value.judgeQuestionIds.push(id)
    } else if (type == 2) {
      delIds.value.multiQuestionIds.push(id)
    } else if (type ==3) {
      delIds.value.fillQuestionIds.push(id)
    }
  })
 ids.value = selection.map(item => item.questionId)
 selectionQuestionType.value = selection.length > 0 ? selection[0].questionType : null
 single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加试题"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _questionId = row?.questionId || ids.value[0]
  const _questionType=row?.questionType || selectionQuestionType.value
  getQuestion({ questionId: _questionId,questionType:_questionType}).then(response => {
        // 强制补全字段，避免缺失导致异常
    form.value = {
      questionId: null,
      course: route.params.course ?? '',
      question: '',
      answer: '',
      analysis: '',
      score: null,
      level: null,
      section: '',
      questionType: null,
      aOption: null,
      bOption: null,
      cOption: null,
      dOption: null,
      ...response.data // 合并接口数据
    }
    open.value = true
    title.value = "修改题库管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      if (form.value.questionId != null) {
        updateQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
    
  if(row.questionType){
    const id=row.questionId
  //清空
  delIds.value = {
    judgeQuestionIds: [],
    multiQuestionIds: [],
    fillQuestionIds: []
  };
  if(row.questionType==1){
      delIds.value.judgeQuestionIds.push(id);
  }else if(row.questionType==2){
      delIds.value.multiQuestionIds.push(id);
  } else if(row.questionType==3){ 
      delIds.value.fillQuestionIds.push(id);
  }
  }

  proxy.$modal.confirm('是否确认删除试题"'  + '"的数据项？').then(function() {
    return delQuestion(delIds.value)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('module/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}


onMounted(() => { 
  if (route.params.course) {
    queryParams.value.course = route.params.course
  }
 getList()
}) 
</script>
